<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

/*
 用户迁移
 4、增加系统迁移页面
   步骤：
   a、微信登录
   b、输入手机号码，提供手机号码验证码
   c、验证成功后，提供：登录密码和支付密码输入页面
   d、提交

*/
class Migration extends Controller{
	
	//查询
    public function index(){
		$request = Request::instance();
		
		//首次进入带参数清理wechat_id
		$clear = $request->param('clear');
		if($clear == '1'){
			Session::delete('wechat_id');
			Cookie::delete('headimg');
		}
		
		//①得到wechat_id
		if(!IS_TEST){
			//当前登陆状态
			if(!Session::has('wechat_id') || !Cookie::has('headimg')){
				$this->wxlogin();
				exit();
			}
		}else{
			//测试
			Session::set('wechat_id','oRDpMt8FvPrZ6gbwoWerEc_5mI_80005');
			Cookie::set('headimg','',7200);//本地测试设置为默认的头像
		}

		//显示页面
		defined('WECHAT_ID') or define('WECHAT_ID',Session::get('wechat_id'));
		
		//②判断wechat_id是否已迁移
		$pm = [
			'wechatid' => WECHAT_ID
		];
		$res = \ServerHelper::post('^/syncuser/update_check',$pm);
		$data = $this->J($res);
		if($data['flag'] == 1){
			//这里得到agentid，并记录，避免进入首页再次登陆
			Session::set('agent_id',$data['data']['agentid']);
			//$this->redirect('Index/index'); exit();
			//不直接跳，提示一下
			//已经做过迁移了，纯粹提示一下
			return view('index_success',['msg'=>$data['msg']]);
		}else if($data['flag'] == 2){
			//代理不能迁移
			return view('index_error',['msg'=>$data['msg']]);
		}
		
		return view('',['smscode_type'=>'register']);
    }
	
	//发送验证码
	public function sendsms(){
		$request = Request::instance();
		if(!Session::has('wechat_id')) ajax('操作失败');
		
		$phonenum = $request->param('phonenum');
		$type = $request->param('type','register');
		
		if(!\RegexHelper::is_phone($phonenum)){
			ajax('手机号输入错误');
		}
		
		//拉取SMS配置
		$response = \ServerHelper::post('GetAliyunSMSInfo',['type'=>$type]);
		$data = $this->J($response);
		$smsconfig = $data['data'];
		//短信参数
		$smscode = rand(1000,9999);
		$param = [
			'code' => $smscode,
		];
		//执行发送
		$hp = new \AliyunSMSHelper($smsconfig['accesskeyid'],$smsconfig['accesskeysecret']);
		if($hp->send($phonenum,$smsconfig['sign'],$smsconfig['templete_code'],$param)){
			//记录验证码，5分钟有效
			Cookie::set('smscode_' . $type,$smscode,300);
			ajax('发送成功',true);
		}
		ajax('短信验证码发送失败');
	}
	
	//验证手机号绑定微信
	public function bindwechat(){
		$request = Request::instance();
		if(!Session::has('wechat_id')) ajax('操作失败');

		$smscode = $request->param('smscode');
		//校验短信码
		$smscode_real = Cookie::get('smscode_register');
		if($smscode != $smscode_real) ajax('短信码错误');
		
		//打开密码设置开关，避免直接进入password里设置密码
		Cookie::set('migration_password','open',3600);
		
		$pm = [
			'wechatid' => Session::get('wechat_id'),
			'phonenum' => $request->param('phonenum'),//手机号
		];
		//检测号码是否绑定过其他微信
		$res = \ServerHelper::post('^/syncuser/update_wechatid_check',$pm);
		$data = $this->J($res);
		
		if($data['flag'] == -1){
			//错误提示
			ajax($data['msg']);
		}else if($data['flag'] == 0){
			//绑定失败
			ajax($data['msg']);
		}else if($data['flag'] == 1){
			//手机号绑定微信成功、跳转设置密码
			Session::set('agent_id',$data['data']['agentid']);
			ajax($data['msg'],true);
		}else if($data['flag'] == 2){
			//该手机号已经绑定过其他微信，直接提示，不做跳转
			ajax($data['msg']);
		}
	}
	
	//登录密码和支付密码输入页面
	public function password(){
		$req = Request::instance();
		
		if($req->isPost()){
			//发送密码设置
			if(!Session::has('agent_id')){
				ajax('操作失败',false,'back');
			}
			defined('AGENT_ID') or define('AGENT_ID',Session::get('agent_id'));
			//使用密码设置开关
			if(Cookie::get('migration_password') != 'open'){
				ajax('验证已过期，请重新操作',false,'back');
			}
			
			$loginpwd1 = $req->param('loginpwd1');
			$loginpwd2 = $req->param('loginpwd2');
			if($loginpwd1 == '' || $loginpwd1 !== $loginpwd2){
				ajax('登陆密码输入错误');
			}
			
			$headimg = Cookie::get('headimg');
			$pm = [
				'agentid' => AGENT_ID,
				'loginpwd' => $loginpwd1,
				'headimg' => $headimg,
			];
			$res = \ServerHelper::post('^/syncuser/update_password',$pm);
			$data = $this->J($res);
			
			if(empty($data['flag'])){
				ajax($data['msg']);
			}
			Cookie::delete('migration_password');
			ajax($data['msg'],true);
		}
		
		if(!Session::has('agent_id') || !Session::has('wechat_id') || !Cookie::has('headimg')){
			$this->redirect('Migration/index',['clear'=>1]);
			exit();
		}
		return view('');
	}
	
	private function J($list){
		$data = json_decode($list,true);
		if(!isset($data['flag'])){
			__log($list,'welogin');
			if(Request::instance()->isAjax()){
				ajax('网络错误');
			}
			exit('net error');
		}
		return $data;
	}
	
	private function wxlogin(){
		if(!__iswechat()){
			$this->error('请在微信中登陆');
		}
		
		$cfg = \ServerHelper::GetWeChatConfig();
		if(!isset($cfg['appid'])){
			__log('登录：没有设置微信appid','weixin');
			$this->error('系统错误');
			exit();
		}
		
		$appid = $cfg['appid'];
		
		$request = Request::instance();
		
		$redirect_uri = urlencode($request->domain() . url('Migration/wechat_redirect'));
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize";
		$url.="?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		
		$this->redirect($url);
	}
	
	public function wechat_redirect(){
		//载入配置信息
		$cfg = \ServerHelper::GetWeChatConfig();
		if(
			!isset($cfg['appid']) || 
			!isset($cfg['appsecret'])
			){
			__log('登录：没有设置微信appid或appsecret','weixin');
			$this->error('系统错误');
			exit();
		}
		$appid = $cfg['appid'];
		$appsecret = $cfg['appsecret'];
		
		//拉取请求
		$request = Request::instance();

		//第一步返回的 得到了 Code
		$code = $request->param('code','');
		if($code == ''){
			$this->error('登录发起失败');
		}

		//第二步：通过code换取网页授权access_token
		$url ="https://api.weixin.qq.com/sns/oauth2/access_token";
		$url.="?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
		$info = $this->getJson($url);
		if(!isset($info['refresh_token'])){
			$this->error('登陆发起失败');
		}

		//第三步：刷新access_token（如果需要）
		$refresh_token = $info['refresh_token'];
		$url = "https://api.weixin.qq.com/sns/oauth2/refresh_token";
		$url.= "?appid=$appid&grant_type=refresh_token&refresh_token=$refresh_token";
		$info = $this->getJson($url);
		if(
			!isset($info['access_token']) || 
			!isset($info['openid'])
		){
			$this->error('登陆发起失败');
		}
		
		//第四步：拉取用户信息(需scope为 snsapi_userinfo)
		$access_token = $info['access_token'];
		$openid = $info['openid'];
		$url = "https://api.weixin.qq.com/sns/userinfo";
		$url.= "?access_token=$access_token&openid=$openid&lang=zh_CN";
		$info = $this->getJson($url);
		if(!isset($info['openid'])){
			$this->error('登陆发起失败');
		}
		
		__log($info,'migration_login');
		
		Session::set('wechat_id',$info['openid']);
		Cookie::set('headimg',$info['headimgurl'],7200);
		$this->redirect('Migration/index');
	}
	
	private function getJson($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output, true);
	}

}
